package com.ougy.reshop.service.impl;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ougy.reshop.model.User;
import com.ougy.reshop.service.ISUser;
import com.ougy.reshop.util.Notice;
import com.ougy.reshop.util.PasswordUtil;

@Service
public class SUser extends BaseServices implements ISUser {
	
	private static final Logger logger = Logger.getLogger(SUser.class);

	public Notice register(User user) {
		Notice notice = new Notice();
		String username = user.getUsername();
		User m = this.userDao.findByUsername(username);
		if ((m != null) && (!m.getUsername().equals(""))) {
			notice.setStatus(false);
			notice.setCode("user exist");
			notice.setTitle("提示");
			notice.setBody("该账号已被使用");
			return notice;
		}
		user.setCreateTime(getTimestamp());
		user.setPassword(PasswordUtil.createPassword(user.getPassword()));
		this.userDao.save(user);
		user = this.userDao.merge(user);
		session.put("user", user);
		notice.setStatus(true);
		notice.setCode("register success");
		notice.setTitle("提示");
		notice.setBody("注册成功");
		return notice;
	}

	@Override
	public User findById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void save(User user) {
		// TODO Auto-generated method stub
 
	}

	@Override
	public Notice login(String username, String password) {
		Notice notice = new Notice();
		User user = userDao.findByUsername(username);
		if (user != null) {
			logger.debug("username："+username+",password:"+password);
			if (PasswordUtil.authenticatePassword(user.getPassword(), password)) {
				this.session.put("user", user);
				notice.setStatus(true);
				notice.setCode("login success");
				notice.setTitle("提示");
				notice.setBody("登陆成功");
				user.setLastTime(getTimestamp());
				this.userDao.merge(user);
			} else {
				notice.setStatus(false);
				notice.setCode("account or password error");
				notice.setTitle("错误");
				notice.setBody("您的用户名或者密码输入错误，请重试");
			}
		} else {
			notice.setStatus(false);
			notice.setCode("account not exist");
			notice.setTitle("错误");
			notice.setBody("该账号不存在");
		}
		return notice;
	}
}
